package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

public class RedisLock implements ILock{
    public static final String PREFIX_KEY = "lock:";
    public static final String PREFIX_VALUE= UUID.randomUUID().toString(true)+"-";
    private String name;
    private StringRedisTemplate stringRedisTemplate;
    public RedisLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }
    @Override
    //利用redis中的setnx来实现分布式锁
    public boolean tryLock(Long expireTime, TimeUnit timeUnit) {
        //获取当前线程id和UUID结合作为存进去的数值，防止释放锁误删情况
        long id = Thread.currentThread().getId();
        String lockKey = PREFIX_KEY + name;
        Boolean success = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, PREFIX_VALUE + id, expireTime, timeUnit);
        return Boolean.TRUE.equals(success);
    }

    @Override
    public void unLock() {
        //删除锁之前要进行对锁的判断
        String threadId = stringRedisTemplate.opsForValue().get(PREFIX_KEY + name);
        String id=PREFIX_VALUE+Thread.currentThread().getId();
        //当两个id完全一致时才能删除
        if(threadId.equals(id)){
            stringRedisTemplate.delete(PREFIX_KEY + name);
        }
    }
}
